package com.dragon.backstage.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.dragon.backstage.service.LoginService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 字段填充处理器
 *
 * @author dragon
 * @version 1.0
 * @date 2024/8/5 13:27
 */
@Slf4j
@Component
public class SaMetaObjectHandler implements MetaObjectHandler {

    @Lazy
    @Resource
    private LoginService loginService;

    /**
     * 插入元对象字段填充（用于插入时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 创建时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
        // 创建者
        this.strictInsertFill(metaObject, "createBy", () -> loginService.getAccount(), String.class);
        // 更新时间
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        // 更新者
        this.strictUpdateFill(metaObject, "updateBy", () -> loginService.getAccount(), String.class);
    }

    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新时间
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        // 更新者
        this.strictUpdateFill(metaObject, "updateBy", () -> loginService.getAccount(), String.class);
    }

}
